﻿/**
 * Copyright (c) 2013 Jeremy Wyman
 * Microsoft Public License (Ms-PL)
 * This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
 * 1. Definitions
 *    The terms "reproduce", "reproduction", "derivative works", and "distribution" have the same meaning here as under U.S. copyright law.
 *    A "contribution" is the original software, or any additions or changes to the software.
 *    A "contributor" is any person that distributes its contribution under this license.
 *    "Licensed patents" are a contributor's patent claims that read directly on its contribution.
 * 2. Grant of Rights
 *    (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
 *    (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
 * 3. Conditions and Limitations
 *    (A) No Trademark License - This license does not grant you rights to use any contributors' name, logo, or trademarks.
 *    (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
 *    (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
 *    (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
 *    (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 *    
 * More info on: http://tempest.codeplex.com
**/

using System;
using System.Collections;
using System.Collections.Generic;

namespace Tempest.Collections
{
    /// <summary>
    /// Represents a collection of keys and values, where the values may or may not be present in memory.
    /// </summary>
    /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
    /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
    public sealed class LazyDictionary<TKey, TValue>
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of Isris.LazyDictionary.
        /// </summary>
        /// <param name="func">The function used to retrieve a TValue for a given TKey.</param>
        public LazyDictionary(Func<TKey, TValue> func) : this(func, 0) { }
        /// <summary>
        /// Initializes a new instance of Isris.LazyDictionary.
        /// </summary>
        /// <param name="func">The function used to retrieve a TValue for a given TKey.</param>
        /// <param name="capcacity">The initial number of elements that the dictionary can contain.</param>
        /// <exception cref="ArgumentNullException">Throws an ArgumentNullException if func is null.</exception>
        public LazyDictionary(Func<TKey, TValue> func, int capcacity)
        {
            #region Argument Validation
            if (func == null)
                throw new ArgumentNullException("func", "The function pointer to load the value cannot be null");
            #endregion
            _func = func;
            _keys = new HashSet<TKey>();
            _values = new Dictionary<TKey, TValue>(capcacity);
        }
        #endregion
        #region Members
        /// <summary>
        /// Gets or sets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key associated with a specific value.</param>
        /// <returns>The value associated with the supplied key.</returns>
        public TValue this[TKey key]
        {
            get
            {
                if (!_keys.Contains(key))
                    throw new KeyNotFoundException();
                //
                if (!_values.ContainsKey(key))
                {
                    TValue value = _func(key);
                    _values.Add(key, value);
                }
                //
                return _values[key];
            }
            set
            {
                if (!_keys.Contains(key))
                    throw new KeyNotFoundException();
                //
                if (_values.ContainsKey(key))
                {
                    _values[key] = value;
                }
                else
                {
                    _values.Add(key, value);
                }
            }
        }
        /// <summary>
        /// The number of key/value pairs in the dictionary.
        /// </summary>
        public int Count { get { return _keys.Count; } }
        /// <summary>
        /// List of the keys contained in the dictionary.
        /// </summary>
        public IEnumerable<TKey> Keys { get { return _keys; } }
        #region Private Members
        private HashSet<TKey> _keys;
        private Func<TKey, TValue> _func;
        private Dictionary<TKey, TValue> _values;
        #endregion
        #endregion
        #region Methods
        /// <summary>
        /// Adds a specified key, but not the value, to the dictionary.
        /// </summary>
        /// <param name="key">The key of the element to add.</param>
        public void Add(TKey key)
        {
            //
            if (_keys.Contains(key))
                throw new ArgumentException("The key is already present in the dictionary");
            //
            _keys.Add(key);
        }
        /// <summary>
        /// Adds the specified key and value to the dictionary.
        /// </summary>
        /// <param name="key">The key of the element to add.</param>
        /// <param name="value">The value of the element to add. The value can be null for reference types.</param>
        public void Add(TKey key, TValue value)
        {
            //
            if (_keys.Contains(key))
                throw new ArgumentException("The key is already present in the dictionary");
            //
            _keys.Add(key);
            _values.Add(key, value);
        }
        /// <summary>
        /// Removes all keys and values from the dictionary
        /// </summary>
        public void Clear()
        {
            _keys.Clear();
            _values.Clear();
        }
        /// <summary>
        /// Determines whether a specific key is present in the dictionary.
        /// </summary>
        /// <param name="key">A specific key that might be present in the dictionary.</param>
        /// <returns>true if the key is present; otherwise false.</returns>
        public bool ContainsKey(TKey key)
        {
            return _keys.Contains(key);
        }
        /// <summary>
        /// Determines whether the value associate with a specific key has been loaded in the dictionary
        /// </summary>
        /// <param name="key">The key of the value that may have been loaded.</param>
        /// <returns>true if the key is present and the value loaded; otherwise false. This method returns false if key is not found in the dictionary.</returns>
        public bool IsLoaded(TKey key)
        {
            return _values.ContainsKey(key);
        }
        /// <summary>
        /// Removes the value with the specified key from the LazyDictionary
        /// </summary>
        /// <param name="key">The key of the element to remove.</param>
        /// <returns>true if the element is successfully found and removed; otherwise, false. This method returns false if key is not found in the dictionary.</returns>
        public bool Remove(TKey key)
        {
            return _keys.Remove(key) || _values.Remove(key);
        }
        /// <summary>
        /// Gets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key of the value to get.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
        /// <returns>true if the dictionary contains an element with the specified key; otherwise, false.</returns>
        public bool TryGetValue(TKey key, out TValue value)
        {
            bool success = _values.ContainsKey(key);
            if (success)
            {
                value = _values[key];
            }
            else
            {
                value = default(TValue);
            }
            return success;
        }
        #endregion
    }
}
